package com.fwj.base.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.fwj.authorization.tenant.CustomTenantHandler;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 分页插件
 *
 * @author zc
 */
@Configuration
@MapperScan("com.*.*.*.mapper")
public class MybatisPlusConfig {
    @Resource
    private CustomTenantHandler customTenantHandler;
    @Value("${custom.tenant.enable}")
    private boolean tenantEnable;

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setDialectType(DbType.MYSQL.getDb());
        // SQL解析处理拦截：增加租户处理回调。
        List<ISqlParser> sqlParserList = new ArrayList<>();
        // 攻击 SQL 阻断解析器、加入解析链
        sqlParserList.add(new BlockAttackSqlParser());
        // 多租户拦截
        if (tenantEnable) {
            TenantSqlParser tenantSqlParser = new TenantSqlParser();
            tenantSqlParser.setTenantHandler(customTenantHandler);
            sqlParserList.add(tenantSqlParser);
        }
        paginationInterceptor.setSqlParserList(sqlParserList);
        return paginationInterceptor;
    }

}